package com.bupt.ilink.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bupt.ilink.controller.FileTranscriptionController;
import com.bupt.ilink.entity.FileTranscriptionTaskResponse;
import com.bupt.ilink.entity.Studyspace.*;
import com.bupt.ilink.entity.Studyspace.DTO.CourseResponse;
import com.bupt.ilink.entity.Studyspace.DTO.StudyCourseFileResponse;
import com.bupt.ilink.entity.Studyspace.DTO.StudySourceFileResponse;
import com.bupt.ilink.mapper.*;
import com.bupt.ilink.service.FileTranscriptionService;
import com.bupt.ilink.service.OssService;
import com.bupt.ilink.service.StudyTeacherCoursesTeacherService;
import com.bupt.ilink.service.bailian.FileService;
import com.bupt.ilink.utils.R;
import com.bupt.ilink.utils.SnowflakeIdGenerator;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bupt.ilink.service.StudyaboutTeacherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//import org.springframework.transaction.TransactionException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Transactional
@Service
@Slf4j
public class StudyaboutTeacherServiceImpl extends ServiceImpl<StudyTeacherCourseMapper, StudyTeacherCourse> implements StudyaboutTeacherService {

    //创建日志记录类实例
    private static final Logger logger = LoggerFactory.getLogger(StudyaboutTeacherServiceImpl.class);
//    public StudyaboutTeacherServiceImpl(StudyCourseFileMapper studyCourseFileMapper,
//                                      StudyTeacherCourseMapper studyTeacherCourseMapper,
//                                      OssService ossService,
//                                      FileService fileService) {
//        this.studyCourseFileMapper = studyCourseFileMapper;
//        this.studyTeacherCourseMapper = studyTeacherCourseMapper;
//        this.ossService = ossService;
//        this.fileService = fileService;
//    }
    @Autowired
    private OssService ossService;
    @Autowired
    private StudyCourseFileMapper studyCourseFileMapper;
    @Autowired
    private StudyTeacherCourseMapper studyTeacherCourseMapper;
    @Autowired
    private CourseSourceMapper courseSourceMapper;
    @Autowired
    private StudyFileSourceMapper studyFileSourceMapper;
    @Autowired
    private StudyTeacherCoursesTeacherService studyTeacherCoursesTeacherService;
    @Autowired
    private StudyWebSourseMapper studyWebSourseMapper;

    @Autowired
    FileService fileService;

    @Autowired
    FileTranscriptionMapper fileTranscriptionMapper;
    @Autowired
    private FileTranscriptionService fileTransService;
    @Autowired
    private FileTranscriptionController fileTranscriptionController;

    @Async("checkVideoTaskExecutor")
    public CompletableFuture<Void> checkVideoStatusAsync(Long courseSourceId) {
        return CompletableFuture.runAsync(() -> {
        int queryNum=0;

        while (true) {
            queryNum+=1;
            boolean latest = refreshVideoStatus(courseSourceId,queryNum); // 你要轮询的函数
            logger.info("文件{}状态更新中...",courseSourceId);
            if (latest) {
                break;
            }
            try {
                // 等待四分钟后再检查，此时线程休眠，不会占用CPU资源
                Thread.sleep(4 * 60 * 1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new IllegalStateException(e);
            }
        }
        });
    }
    //另一种处理方式：使用定时任务进行查询
    // 每4分钟检查一次视频状态
//    @Scheduled(fixedRate = 4 * 60 * 1000)
//    public void checkVideoStatus() {
//        List<CourseSource> courseSourceIds = courseSourceMapper.selectList(
//                new QueryWrapper<CourseSource>().eq("transcription_complete", false)
//        ); // 获取需要检查的视频ID
//        if (courseSourceIds != null) {
//            for (CourseSource courseSourceId : courseSourceIds) {
//                log.info("正在检查文件 " + courseSourceId + " 的状态...");
//                boolean latest = refreshVideoStatus(courseSourceId.getCourseSourceId()); // 调用轮询方法
//                if (latest) {
//                    System.out.println("文件 " + courseSourceId + " 状态已更新");
//                } else {
//                    System.out.println("文件 " + courseSourceId + " 状态未更新");
//                }
//            }
//
//        }
//    }


    private boolean refreshVideoStatus(Long courseSourceId,int queryNum) {
        // 返回 true 表示文件状态已更新，轮询结束
        CourseSource courseSource = courseSourceMapper.selectById(courseSourceId);
        //特殊情况，甚至都没有上传时，不进行轮询
        if (!courseSource.getOssWriteStatus()){
            return true;
        }
        //如果加工失败，即加工已经停止
        if (courseSource.getTranscriptionCompleteStatus()){
            return true;
        }
        // 判断已上传未加工完的音视频资源的状态
        if (!courseSource.getTranscriptionComplete() ) {
            String taskId = courseSource.getTaskId();
            if (taskId != null && !taskId.isEmpty() ) {
                Jugehandlevideostate(courseSource.getTaskId(),queryNum);
                //再次查询
                courseSource = courseSourceMapper.selectById(courseSourceId);
                return courseSource.getTranscriptionComplete() || courseSource.getTranscriptionCompleteStatus();

            }
            return false;
        } //当加工状态为true时，直接返回true
        return true;
    }


    @Override
    public boolean newcreateChapter(String fileName, Long courseFileId, Integer sortOrder) throws Exception {
        SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);

        // 创建课程对应的文件夹
        StudyCourseFile courseFile = new StudyCourseFile();
        courseFile.setCourseFileId(idGenerator.nextId());
        courseFile.setName(fileName);

        // 根据 courseId 查询父文件夹的路径
        StudyCourseFile parent_file = studyCourseFileMapper.selectById(courseFileId);
        courseFile.setParentId(parent_file.getCourseFileId());
        String file_path = parent_file.getFilePath() + courseFile.getCourseFileId() + "/";
        courseFile.setFilePath(file_path);
        courseFile.setLevel(parent_file.getLevel() + 1);
        courseFile.setCourseId(parent_file.getCourseId());

        // 在前端传递的 sortOrder 基础上加 1
        int newSortOrder = sortOrder + 1;
        courseFile.setSortOrder(newSortOrder);

        // 插入新章节到数据库
        studyCourseFileMapper.insert(courseFile);

        // 更新父文件夹, 增加层级关系
        parent_file.setChildId(courseFile.getCourseFileId());
        studyCourseFileMapper.updateById(parent_file);

        // 向RAG添加文件夹
        fileService.createCategory(parent_file.getFilePath(), courseFile.getCourseFileId() + "/");

        // 向OSS添加文件夹
        return ossService.createDirectory(String.valueOf(courseFile.getCourseFileId()) + "/", parent_file.getFilePath());
    }



    @Transactional
    @Override
    public boolean createCourseWithFolder(String userid, CourseResponse newTeacherCourse,
                                          List<MultipartFile> files) throws Exception {
        StudyTeacherCourse course = new StudyTeacherCourse();
//        StudyTeacherCoursesTeacher coursesTeacher = new StudyTeacherCoursesTeacher();

        //  雪花算法分配id
        SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
        course.setCourseId(idGenerator.nextId());
        course.setCourseName(newTeacherCourse.getCourseName());
        course.setCourseTag(newTeacherCourse.getCourseTag());
//        course.setCourseImage(newTeacherCourse.getCourseImage());
        course.setCourseDescription(newTeacherCourse.getCourseDescription());
        course.setViewNum(0L);
        course.setCreatedAt(new Date());

        // 创建课程对应的文件夹
        StudyCourseFile courseFile = new StudyCourseFile();
        courseFile.setCourseFileId(idGenerator.nextId());
        courseFile.setName(course.getCourseName());
        String file_path=userid+"/" + courseFile.getCourseFileId() +"/";
        courseFile.setFilePath(file_path);
        courseFile.setLevel(0);

        if (studyCourseFileMapper.insert(courseFile)>0){
            logger.info("用户'{}'课程创建文件夹成功:{}",userid,courseFile);
        }else {
            logger.error("用户'{}'课程创建文件夹失败:{}",userid,courseFile);
        }

        //写入课程基本信息
        // 获取刚刚创建的文件夹ID并设置到课程中
        course.setFolderId(courseFile.getCourseFileId());
        course.setTeacherId(userid);


        // 创建课程，继承了对应的表StudyTeacherCourse可以直接写入
        this.save(course);
        //由于外键关联得后续再加入
        courseFile.setCourseId(course.getCourseId());
        studyCourseFileMapper.updateById(courseFile);

        String filePath = userid + "/" + courseFile.getCourseFileId() + "/";
        // 处理文件上传到OSS
        if (files != null && !files.isEmpty()) {
            // 上传第一个文件作为 courseImage
            MultipartFile courseImageFile = files.get(0);
            String courseImageName = course.getCourseId() + getFileExtension(courseImageFile.getOriginalFilename());
            boolean courseImageUploadResult = ossService.uploadFile(courseImageFile, filePath, courseImageName);
            if (courseImageUploadResult) {
                course.setCourseImage(filePath + courseImageName);
            }

            // 上传剩余的文件作为每个 teacher 的 teacherImage
            List<StudyTeacherCoursesTeacher> teachers = newTeacherCourse.getTeacher();
            for (int i = 1; i < files.size(); i++) {
                MultipartFile teacherImageFile = files.get(i);
                StudyTeacherCoursesTeacher teacher = teachers.get(i - 1); // 第一个文件是 courseImage，从第二个文件开始对应 teacher
                // 保存教师信息到数据库
                teacher.setId(idGenerator.nextId());
                teacher.setCourseId(course.getCourseId());

                String teacherImageName = "teacher" + teacher.getId() + getFileExtension(teacherImageFile.getOriginalFilename());
                boolean teacherImageUploadResult = ossService.uploadFile(teacherImageFile, filePath, teacherImageName);
                if (teacherImageUploadResult) {
                    teacher.setTeacherImage(filePath + teacherImageName);
                }

                if (studyTeacherCoursesTeacherService.save(teacher)){
                    logger.info("用户'{}'课程创建关联教师成功:{}",userid,teacher);
                }else {
                    logger.error("用户'{}'课程创建关联教师失败:{}",userid,teacher);
                }
            }
        }

        // 更新课程表中的 courseImage
        if (course.getCourseImage() != null) {
            this.updateById(course);
        }
//        StudyTeacherCourse studyTeacherCourse = new StudyTeacherCourse();
//        studyTeacherCourse.setCourseId(idGenerator.nextId());
//        studyTeacherCourse.setTeacherId(userid);
//        studyTeacherCourse.setFolderId(courseFile.getCourseFileId());
//        studyTeacherCourse.setCourseName(course.getCourseName());
//        studyTeacherCour+se.setCourseDescription(course.getCourseDescription());
//        studyTeacherCourse.setCourseSchedule(course.getCourseSchedule());
//        studyTeacherCourse.setCourseTag(course.getCourseTag());
        //为用户账户创建用户路径
//        ossService.createDirectory(course.getTeacherId()+"/", "");
        //写入OSS String.valueOf(courseFile.getCourseFileId())
        //向RAG添加文件夹
        try {
            fileService.createCategory("", userid+"/");
        }
        catch (Exception e){
            System.out.println("RAG创建用户路径出错:"+e.getMessage());
        }
        System.out.println(userid+"/");
        System.out.println(course.getFolderId() +"/");

        fileService.createCategory(userid+"/", course.getFolderId() +"/");
        return ossService.createDirectory(course.getFolderId() +"/", userid+"/");
    }

    @Transactional
    @Override
    public boolean updateCourseById(String userId, Long courseId, CourseResponse updatedTeacherCourse,
                                    List<MultipartFile> files){
        try{
            SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
            // 从数据库中查找要更新的课程
            StudyTeacherCourse existingCourse = studyTeacherCourseMapper.selectById(courseId);
            if (existingCourse == null) {
                log.error("课程不存在，无法更新，ID：" + courseId);
                return false;
            }

            // 更新课程的基本信息
            existingCourse.setCourseName(updatedTeacherCourse.getCourseName());
            existingCourse.setCourseTag(updatedTeacherCourse.getCourseTag());
            existingCourse.setCourseDescription(updatedTeacherCourse.getCourseDescription());
            existingCourse.setTeacherId(userId);
            existingCourse.setUpdatedAt(new Date()); // 假设有一个更新时间字段


            // 更新对应的文件夹名称
            StudyCourseFile courseFile = studyCourseFileMapper.selectById(existingCourse.getFolderId());
            if (courseFile != null) {
                courseFile.setName(updatedTeacherCourse.getCourseName());  // 使用新的课程名称作为文件夹名称
                studyCourseFileMapper.updateById(courseFile);  // 更新文件夹名称到数据库
            } else {
                log.error("无法找到课程对应的文件夹，ID：" + existingCourse.getFolderId());
                return false;
            }

            // 处理课程文件的路径
            String filePath = userId + "/" + existingCourse.getFolderId() + "/";

            // 更新文件到OSS，如果上传了新的文件
            if (files != null && !files.isEmpty()) {
                // 更新第一个文件作为 courseImage
                MultipartFile courseImageFile = files.get(0);
                String courseImageName = courseId + getFileExtension(courseImageFile.getOriginalFilename());
                boolean courseImageUploadResult = ossService.uploadFile(courseImageFile, filePath, courseImageName);
                if (courseImageUploadResult) {
                    existingCourse.setCourseImage(filePath + courseImageName);
                }

                // 首先根据 courseId 查询所有教师信息
                List<StudyTeacherCoursesTeacher> existingTeachers = studyTeacherCoursesTeacherService.list(
                        new LambdaQueryWrapper<StudyTeacherCoursesTeacher>()
                                .eq(StudyTeacherCoursesTeacher::getCourseId, courseId)
                );

                // 删除OSS中的旧教师图片文件
                for (StudyTeacherCoursesTeacher teacher : existingTeachers) {
                    if (teacher.getTeacherImage() != null) {
                        // 获取 teacherImage 字段存储的完整路径
                        String teacherImagePath = teacher.getTeacherImage();

                        // 提取路径和文件名
                        int lastSlashIndex = teacherImagePath.lastIndexOf('/');
                        if (lastSlashIndex != -1) {
                            String path = teacherImagePath.substring(0, lastSlashIndex + 1);  // 获取文件路径
                            String fileName = teacherImagePath.substring(lastSlashIndex + 1);  // 获取文件名
                            System.out.println("删除OSS中的教师图片");
                            System.out.println("path"+path);
                            System.out.println("fileName"+fileName);
                            boolean ossDeleteResult = ossService.deleteFile(fileName, path);
                            if (ossDeleteResult) {
                                logger.info("成功删除OSS中的教师图片: {}", teacherImagePath);
                            } else {
                                logger.error("删除OSS中的教师图片失败: {}", teacherImagePath);
                            }
                        } else {
                            logger.error("无法解析教师图片路径: {}", teacherImagePath);
                        }
                    }
                }

                // 删除数据库中所有与 courseId 相关的教师信息
                studyTeacherCoursesTeacherService.remove(
                        new LambdaQueryWrapper<StudyTeacherCoursesTeacher>()
                                .eq(StudyTeacherCoursesTeacher::getCourseId, courseId)
                );

                // 重新上传新的教师信息
                List<StudyTeacherCoursesTeacher> teachers = updatedTeacherCourse.getTeacher();
                for (int i = 1; i < files.size(); i++) {
                    MultipartFile teacherImageFile = files.get(i);
                    StudyTeacherCoursesTeacher teacher = teachers.get(i - 1);  // 第一个文件是 courseImage，从第二个文件开始对应 teacher

                    // 新增教师信息，生成新的教师ID
                    teacher.setId(idGenerator.nextId());
                    teacher.setCourseId(courseId);

                    // 生成教师图片名称并上传到OSS
                    String teacherImageName = "teacher" + teacher.getId() + getFileExtension(teacherImageFile.getOriginalFilename());
                    boolean teacherImageUploadResult = ossService.uploadFile(teacherImageFile, filePath, teacherImageName);
                    if (teacherImageUploadResult) {
                        teacher.setTeacherImage(filePath + teacherImageName);
                    }

                    // 保存教师信息到数据库
                    if (studyTeacherCoursesTeacherService.save(teacher)) {
                        logger.info("用户'{}'课程创建关联教师成功:{}", userId, teacher);
                    } else {
                        logger.error("用户'{}'课程创建关联教师失败:{}", userId, teacher);
                    }
                }
            }

            // 更新课程信息到数据库
            studyTeacherCourseMapper.updateById(existingCourse);

            // 如果更新成功，返回 true
            return true;
        }catch (Exception e){
            log.error(e.getMessage());
            return false;
        }
    }

    // 获取文件后缀的方法
    private String getFileExtension(String fileName) {
        if (fileName == null) {
            return "";
        }
        int dotIndex = fileName.lastIndexOf('.');
        return dotIndex == -1 ? "" : fileName.substring(dotIndex);
    }


    //直接关联删除所有的资源了
//    @Transactional
//    @Override
//    public boolean deleteCoursefile(Long courseFileId,Long courseId) throws Exception {
//        // 删除课程对应的文件夹和层级资源，删除对应的OSS
//        //直接删除父文档的ID即可，数据库自身会将子文件夹和资源关联删除  ON DELETE CASCADE
//        //获取该文件夹
//        StudyCourseFile courseFile = studyCourseFileMapper.selectById(courseFileId);
//        if (courseFile != null) {
//            // 删除文件夹
//            ossService.deleteDirectory(courseFile.getFilePath());
//            //RAG上删除
//            fileService.deleteCategory(courseFile.getFilePath());
//
//            //删除资源的转写，听悟
//            //删除对应资源表，同时音视频资源表删除对应的关联转写
//            studyFileSourceMapper.delete(new QueryWrapper<StudyFileSource>().eq("course_id",courseId));
//            courseSourceMapper.deleteCourseResourcesByCourseId(courseId);
//
////            courseSourceMapper.delete(new QueryWrapper<CourseSource>().eq("course_id",courseId));
//            // 课程文件夹，则同时删除课程
//            if (courseFile.getLevel()<=0){
//                this.removeById(courseId);
//            }
//            //层级删除文件夹
//            studyCourseFileMapper.deleteById(courseFileId);
//            return true;
//        }
//        return false;
//    }
    //递归删除文件夹下对应的所有子文件夹和资源
    @Transactional
    @Override
    public boolean deleteCoursefileBycourseFile(Long courseFileId,Long courseId) throws Exception {
        // 删除课程对应的文件夹和层级资源，删除对应的OSS
        //直接删除父文档的ID即可，数据库自身会将子文件夹和资源关联删除  ON DELETE CASCADE
        //获取该文件夹
        StudyCourseFile courseFile = studyCourseFileMapper.selectById(courseFileId);
        if (courseFile != null) {
            //RAG上删除
            try {
                //TODO 加一个路径判断逻辑，rag里是否有
                R rag_result=fileService.deleteCategory(courseFile.getFilePath());
                if (rag_result.getCode()==1){
                    logger.info("删除RAG文件夹{}时成功.",courseFile.getFilePath());
                }else{
                    logger.error("删除RAG文件夹{}时失败，错误原因{}",courseFile.getFilePath(),rag_result.getData());
                }
            }
            catch (Exception e){
                logger.error("删除RAG文件夹{}时发生异常，异常信息{}",courseFile.getFilePath(),e.getMessage());
            }

            //递归删除资源的转写，听悟
            //删除对应资源表，同时音视频资源表删除对应的关联转写
            deleteCourseFilesAndResources(courseFileId);
            //删除web对应资源

//          courseSourceMapper.delete(new QueryWrapper<CourseSource>().eq("course_id",courseId));
            //删除课程元信息中关联的文件夹
            if (courseFile.getLevel()<=0){
                if (studyTeacherCourseMapper.clearFolderIdByCourseId(courseId)>0){
                    logger.info("成功解除课程{}与文件夹的关联",courseId);
                }else {
                    logger.error("解除课程{}与文件夹的关联失败",courseId);
                }

            }
            //层级删除文件夹
            if (studyCourseFileMapper.deleteById(courseFileId)>0){
                logger.info("成功递归删除文件夹{}",courseFileId);
            }else {
                logger.error("递归" +
                        "删除文件夹{}失败",courseFileId);
            }

            // 课程文件夹，则最后删除课程，因为都与课程做了外键关联
            if (courseFile.getLevel()<=0){
//                this.removeById(courseId);//这一步有问题
                if ((studyTeacherCourseMapper.deleteById(courseId))>0){
                    logger.info("成功注销课程{}",courseId);
                }else {
                    logger.error("注销课程{}失败",courseId);
                }
//                    studyTeacherCourseMapper.delete(new QueryWrapper<StudyTeacherCourse>().eq("course_id",courseId));
            }

            // 删除文件夹
            try{
                //TODO 加一个路径判断逻辑，OSS里是否有
                if(ossService.deleteDirectory(courseFile.getFilePath())){
                    logger.info("删除OSS文件夹{}时成功.",courseFile.getFilePath());
                }else{
                    logger.error("删除OSS文件夹{}时失败",courseFile.getFilePath());
                }
            }
            catch (Exception e){
                logger.error("删除OSS文件夹{}时发生异常，异常信息{}",courseFile.getFilePath(),e.getMessage());
            }

            return true;
        }
        return false;
    }


    // 递归删除课程文件夹及其关联数据
    @Transactional
    public void deleteCourseFilesAndResources(Long courseFileId) throws Exception {
        try {
            // 先删除当前文件夹的关联数据
            boolean relatedResourcesDeleted = deleteRelatedResources(courseFileId);
            if (relatedResourcesDeleted) {
                logger.info("成功删除文件夹{}下的所有资源文件", courseFileId);
            } else {
                logger.warn("删除文件夹{}下的所有资源文件失败", courseFileId);
            }

            // 获取当前文件夹的子文件夹ID
            List<StudyCourseFile> childFolderIds = studyCourseFileMapper.selectList(
                    new QueryWrapper<StudyCourseFile>().eq("parent_id", courseFileId)
            );


            // 递归删除子文件夹及其关联数据
            for (StudyCourseFile childFolderId : childFolderIds) {
                deleteCourseFilesAndResources(childFolderId.getCourseFileId());
                logger.info("成功删除文件夹{}下资源 ", childFolderId.getName());
            }

            // 这里不需要删除当前文件夹，后续再递归删除
//            int deleteCount = studyCourseFileMapper.deleteById(courseFileId);
//            if (deleteCount > 0) {
//                logger.info("成功删除文件夹{}", courseFileId);
//            } else {
//                logger.warn("Failed to delete course file with courseFileId: {}", courseFileId);
//            }
//            //先删除当前文件夹的关联数据
//            deleteRelatedResources(courseFileId);
//
//            // 获取当前文件夹的子文件夹ID
//            List<StudyCourseFile> childFolderIds = studyCourseFileMapper.selectList(new QueryWrapper<StudyCourseFile>().eq("parent_id",courseFileId));
//
//
//            // 递归删除子文件夹及其关联数据
//            for (StudyCourseFile childFolderId : childFolderIds) {
//                deleteCourseFilesAndResources(childFolderId.getCourseFileId());
//            }
            // 删除当前文件夹
//        studyCourseFileMapper.deleteById(courseFileId);
        }
        catch (Exception e) {
            logger.error("删除课程文件{}失败:, error={}", courseFileId, e.getMessage(), e);
            throw new Exception("删除课程文件及其关联资源时失败");

        }

    }

    // 删除当前文件夹的关联资源数据，add web
    @Transactional
    protected Boolean deleteRelatedResources(Long courseFileId) throws Exception {
        try {
            // 初始化删除计数器
            int deleteCount = 0;
            //删除web
            deleteCount +=studyWebSourseMapper.delete(new QueryWrapper<StudyWebSourse>().eq("file_id",courseFileId));
            // 删除 coursesource 表中与当前文件夹相关的数据,音视频资源表删除对应的关联转写
    //        CourseSource courseSource=courseSourceMapper.selectOne()
            deleteCount +=courseSourceMapper.deleteCourseResourcesBycourseFileId(courseFileId);
            deleteCount +=courseSourceMapper.deleteCourseResourcesBycourseFileIdNoTask(courseFileId);
    //        courseSourceMapper.delete(new QueryWrapper<CourseSource>().eq("file_id",courseFileId));
            // 删除 study_filesource 表中与当前文件夹相关的数据
            deleteCount +=studyFileSourceMapper.delete(new QueryWrapper<StudyFileSource>().eq("file_id",courseFileId));

            return deleteCount>=3;//删除成功
            }
        catch (Exception e) {
            logger.error("删除课程文件夹关联{}所关联的资源时失败: error={}", courseFileId, e.getMessage(), e);
            throw new RuntimeException("删除课程文件对应资源时失败");
        }
    }


    @Override
    @Transactional
    public boolean deleteSourcesfile(Long sourceId, String type) throws Exception {
        if (type.equals("音视频")){
            CourseSource courseSource = courseSourceMapper.selectById(sourceId);
            String filePath = courseSource.getFilesourcePath();

            // 查找最后一个斜杠的位置
            int lastSlashIndex = filePath.lastIndexOf('/');

            // 使用substring方法进行拆分
            String directory = filePath.substring(0, lastSlashIndex + 1);
            String fileName = filePath.substring(lastSlashIndex + 1);
            if (courseSource != null) {
                if (courseSource.getOssWriteStatus()) {
                    //删除视频对应的OSS
                    if (ossService.deleteFile(fileName, directory)) {
                        logger.info("OSS成功删除视频文件{}", courseSource.getFileName());
                    }else {
                        logger.error("OSS删除视频文件{}失败", courseSource.getFileName());
                    }
                }

                if (courseSource.getTranscriptionComplete()) {
                    //删除视频对应的转写结果和音视频mysql元信息
                    if (courseSourceMapper.deleteCourseResourcesBySourCeId(sourceId)>0) {
                        logger.info("MYSQL成功删除视频文件{}", courseSource.getFileName());
                    }else {
                        logger.error("MYSQL删除视频文件{}失败", courseSource.getFileName());
                    }

                    //RAG中删除
                    // 找到最后一个点的位置
                    int dotIndex = fileName.lastIndexOf('.');
                    // 如果文件名有扩展名，将其替换为 .txt
                    if (dotIndex != -1) {
                        fileName = fileName.substring(0, dotIndex) + ".txt";
                    } else {
                        // 如果没有扩展名，直接添加 .txt
                        fileName = fileName + ".txt";
                    }
                    R rag_result=fileService.deleteFile(directory, fileName);
                    if (rag_result.getCode()==1){
                        logger.info("删除RAG文件夹{}时成功.",courseSource.getFileName());
                    }else{
                        logger.error("删除RAG文件夹{}时失败，错误原因{}",courseSource.getFileName(),rag_result.getData());
                    }
                }else{
                    if (courseSourceMapper.deleteCourseResourcesBycourseSourceIdNoTask(sourceId)>0) {
                        logger.info("MYSQL成功删除视频文件{}", courseSource.getFileName());
                    }else {
                        logger.error("MYSQL删除视频文件{}失败", courseSource.getFileName());
                    }
                }

                return true;
            }
            else {
                return false;
            }
        }else if (type.equals("文档")){
            StudyFileSource studyCourseFile = studyFileSourceMapper.selectById(sourceId);
            if (studyCourseFile != null) {

            //删除MYsql中元信息
//            studyFileSourceMapper.delete(new QueryWrapper<StudyFileSource>().eq("filesource_id",sourceId));
            if (studyFileSourceMapper.delete(new QueryWrapper<StudyFileSource>().eq("filesource_id",sourceId))>0) {
                logger.info("MYSQL成功删除文档文件{}", studyCourseFile.getFileName());
            }else {
                logger.error("MYSQL删除文档文件{}失败", studyCourseFile.getFileName());
            }

            String filePath =studyCourseFile.getFilesourcePath();
            // 查找最后一个斜杠的位置
            int lastSlashIndex = filePath.lastIndexOf('/');
            // 使用substring方法进行拆分
            String directory = filePath.substring(0, lastSlashIndex + 1);
            String fileName = filePath.substring(lastSlashIndex + 1);
            System.out.println(directory);
            System.out.println(fileName);
            //删除文档对应的OSS
            if (studyCourseFile.getOssWriteStatus()) {
//                ossService.deleteFile(fileName, directory);
                if (ossService.deleteFile(fileName, directory)) {
                    logger.info("OSS成功删除文档文件{}", studyCourseFile.getFileName());
                }else {
                    logger.error("OSS删除文档文件{}失败", studyCourseFile.getFileName());
                }
            }
            //RAG中删除
            if (studyCourseFile.getRagCompleteStatus()) {
                if (fileService.deleteFile(directory, fileName).getCode()==1){
                    logger.info("删除RAG文档文件{}时成功.",studyCourseFile.getFileName());
                }else{
                    logger.error("删除RAG文档文件{}时失败，错误原因{}",studyCourseFile.getFileName(),fileService.deleteFile(directory, fileName).getData());
                }
//                fileService.deleteFile(directory, fileName);
            }

            return true;

            } else {
                return false;
            }
        } else if (type.equals("网页")) {
            StudyWebSourse webSourse = studyWebSourseMapper.selectById(sourceId);
            if(webSourse != null){
                studyWebSourseMapper.deleteById(sourceId);
                return true;
            }
            return false;
        }
        return false;
    }

    @Override
    public List<String> getCommonTags() { return studyTeacherCourseMapper.getCommonTags(); }


    @Override
    @Transactional
    public boolean deleteCourse(Long course_id) {
        // 删除课程对应的文件夹和层级资源，删除对应的OSS，删除课程的元信息表
        StudyTeacherCourse courseFile = studyTeacherCourseMapper.selectById(course_id);
        if (courseFile != null) {
            //删除文件夹,删除最大父文件夹，mysql自动关联删除所有的子文件夹
            int result=studyCourseFileMapper.deleteById(courseFile.getFolderId());
            if (result>0){
                // 删除OSS文件夹
                boolean deleteResult=ossService.deleteDirectory(courseFile.getTeacherId()+"/"+courseFile.getFolderId()+"/");
                if (!deleteResult){
                    return false;
                }
                //删除RAG文件夹


                // 最后删除课程元信息表StudyTeacherCourse，同时mysql自动删除对应的所有资源
                this.removeById(course_id);//删除对应的转写资源,资源文件已经关联了外键，所以删除课程时会自动关联删除
            }else{
                return false;
            }
            return true;
        }
        return false;
    }


    @Override
    public boolean createChapter(String fileName, Long courseFileId) throws Exception {
        SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
        // 创建课程对应的文件夹
        StudyCourseFile courseFile = new StudyCourseFile();
        courseFile.setCourseFileId(idGenerator.nextId());
        courseFile.setName(fileName);
        //根据courseId查询父文件夹的路径
        StudyCourseFile parent_file = studyCourseFileMapper.selectById(courseFileId);
        courseFile.setParentId(parent_file.getCourseFileId());
        String file_path=parent_file.getFilePath()+ courseFile.getCourseFileId() +"/";
        courseFile.setFilePath(file_path);
        courseFile.setLevel(parent_file.getLevel()+1);
        courseFile.setCourseId(parent_file.getCourseId());
        studyCourseFileMapper.insert(courseFile);

        //更新父文件夹,增加层级关系
        parent_file.setChildId(courseFile.getCourseFileId());
        studyCourseFileMapper.updateById(parent_file);

        //向RAG添加文件夹
        fileService.createCategory(parent_file.getFilePath(), courseFile.getCourseFileId() +"/");
        //向OSS添加文件夹
        return ossService.createDirectory(String.valueOf(courseFile.getCourseFileId())+"/", parent_file.getFilePath());

    }

    @Override
    public List<StudyCourseFileResponse> getCourseFiles(Long courseFileId, String sentence) {
        // 从文件表中获取在 courseFileId 下的那些子文件夹，并按照 sortOrder 排序
        List<StudyCourseFile> studyCourseFiles = studyCourseFileMapper.selectList(
                new QueryWrapper<StudyCourseFile>()
                        .eq("parent_id", courseFileId)
                        .orderByAsc("sort_order")
        );

        List<StudyCourseFileResponse> responseList = new ArrayList<>();
        for (StudyCourseFile studyCourseFile : studyCourseFiles) {
            StudyCourseFileResponse response = new StudyCourseFileResponse();
            response.setCourseFileId(studyCourseFile.getCourseFileId());
            response.setName(studyCourseFile.getName());
            response.setCreatedAt(studyCourseFile.getCreatedAt());
            response.setFilePath(studyCourseFile.getFilePath());
            response.setLevel(studyCourseFile.getLevel());
            response.setChildId(studyCourseFile.getChildId());
            response.setParentId(studyCourseFile.getParentId());
            response.setCourseId(studyCourseFile.getCourseId());
            response.setSortOrder(studyCourseFile.getSortOrder());

            // 递归获取当前文件夹的子文件夹
            List<StudyCourseFileResponse> childFiles = getCourseFiles(studyCourseFile.getCourseFileId(), sentence);
            response.setChildFiles(childFiles);

            long folderId = studyCourseFile.getCourseFileId();
            List<StudySourceFileResponse> studySourceFileResponses = getSourseFiles(folderId,"");
            response.setSourceFiles(studySourceFileResponses);

            //获取网页资源
            List<StudyWebSourse> webSourse = studyWebSourseMapper.getWebByCourseFileId(folderId);
            response.setWebSourses(webSourse);

            responseList.add(response);
        }

        // 依据 sentence 对 List<StudyCourseFileResponse> 中的 Name 进行过滤
        if (sentence != null && !sentence.isEmpty()) {
            responseList = responseList.stream()
                    .filter(response -> response.getName().contains(sentence))
                    .collect(Collectors.toList());
        }

        return responseList;
    }
    /*@Override
    public List<StudyCourseFileResponse> getCourseFiles(Long courseFileId,String sentence) {
        //从文件表中获取在courseFileId下的那些子文件夹
        List<StudyCourseFile> studyCourseFiles = studyCourseFileMapper.selectList(new QueryWrapper<StudyCourseFile>().eq("parent_id", courseFileId));
        List<StudyCourseFileResponse> responseList=new ArrayList<>();
        for (StudyCourseFile studyCourseFile : studyCourseFiles) {
            StudyCourseFileResponse response = new StudyCourseFileResponse();
            response.setCourseFileId(studyCourseFile.getCourseFileId());
            response.setName(studyCourseFile.getName());
            response.setCreatedAt(studyCourseFile.getCreatedAt());
            response.setFilePath(studyCourseFile.getFilePath());
            response.setLevel(studyCourseFile.getLevel());
            response.setChildId(studyCourseFile.getChildId());
            response.setParentId(studyCourseFile.getParentId());
            response.setCourseId(studyCourseFile.getCourseId());
            responseList.add(response);
        }
        //依据sentence对 List<StudyCourseFileResponse>中的Name进行过滤
        if (sentence != null && !sentence.isEmpty()) {
            responseList = responseList.stream()
                    .filter(response -> response.getName().contains(sentence))
                    .collect(Collectors.toList());
        }
        return responseList;
    }*/
    @Override
    public List<StudyCourseFileResponse> getUserCourseByuserId(String userId,String sentence) {
        // 获取用户有关的所有课程信息
        List<StudyTeacherCourse> courses = studyTeacherCourseMapper.getCourseByteacherId(userId);

        List<StudyCourseFileResponse> courseFile = new ArrayList<>();
        for (StudyTeacherCourse course : courses) {
            //课程不包含文件夹时该目录已经存在异常，不显示
            if (course.getFolderId()!=null){
            StudyCourseFile folder =  studyCourseFileMapper.getCourseFileById(course.getFolderId());
            if (folder!=null) {
                    StudyCourseFileResponse response = new StudyCourseFileResponse();
                    response.setCourseId(course.getCourseId());
                    response.setCourseFileId(course.getFolderId());
                    response.setName(folder.getName());
                    response.setCreatedAt(folder.getCreatedAt());
                    response.setFilePath(folder.getFilePath());
                    response.setLevel(folder.getLevel());
                    response.setTag(course.getCourseTag());
                    response.setChildId(folder.getChildId());
                    String fileUrl = ossService.getFileUrl(course.getCourseImage());
                    response.setCourseImageUrl(fileUrl);
//            response.setTag(folder.ge);
                    courseFile.add(response);
                }
            }else {
                //视为课程未被删除，状态异常，执行删除课程
                studyTeacherCourseMapper.delete(new QueryWrapper<StudyTeacherCourse>().eq("course_id",course.getCourseId()));
            }
        }
        if (sentence != null && !sentence.isEmpty()) {
            courseFile = courseFile.stream()
                    .filter(response -> response.getName().contains(sentence))
                    .collect(Collectors.toList());
        }
        return courseFile;
    }

    @Override
    public R handlefileTrans(CourseSource courseSource, String fileUrl) {
        boolean diarization_enabled =true;
        int speaker_count=mapSpeakerTypeToNumber(courseSource.getSpeakerType());
        List<String> language=convertLanguageStringToList(courseSource.getLanguage());

        FileTranscriptionTaskResponse result = fileTransService.createFileTransTask(
                fileUrl,
                diarization_enabled,
                speaker_count,courseSource.getIsTranslated(),
                language);
        //将转写结果关联到coursesource表
        courseSource.setTaskId(result.getTaskId());
        if (result.getTaskStatus().equals("COMPLETED")){
            courseSource.setTranscriptionComplete(true);
            courseSource.setTranscriptionCompleteStatus(true);
        } else if (result.getTaskStatus().equals("FAILED")) {
            courseSource.setTranscriptionCompleteStatus(true);
            logger.info("音视频{}加工失败原因{}：",result.getTaskId() ,result.getErrorMessage());
        }
        courseSourceMapper.updateById(courseSource);
        return R.ok(result);
    }


    private int mapSpeakerTypeToNumber(String speakerType) {
        return switch (speakerType) {
            case "暂不体验" -> 0;
            case "单人演讲" -> 0;
            case "2人对话" -> 2;
            case "多人讨论" -> 0;
            default -> throw new IllegalArgumentException("Unknown speaker type: " + speakerType);
        };
    }

    private List<String> convertLanguageStringToList(String languageString) {
        if (languageString == null || languageString.isEmpty()) {
            return Arrays.asList(); // 返回空列表
        }
        return Arrays.asList(languageString.split("-"));
    }

    @Override
    public List<StudyCourseFileResponse> getUserCourseResourceTree(String userId) {
        // 获取用户有关的所有课程信息
        List<StudyTeacherCourse> courses = studyTeacherCourseMapper.getCourseByteacherId(userId);

        List<StudyCourseFileResponse> courseResourceTrees = new ArrayList<>();

        for (StudyTeacherCourse course : courses) {
            // 获取课程对应的根文件夹
            StudyCourseFileResponse rootFolder = buildFileTree(course.getFolderId());

            // 设置课程信息到根文件夹
            if (rootFolder != null) {
                rootFolder.setTag(course.getCourseTag());
                courseResourceTrees.add(rootFolder);
            }
        }
        return courseResourceTrees;
    }

    public StudyCourseFileResponse getCourseTree(String userId, Long courseId){
        StudyTeacherCourse course = studyTeacherCourseMapper.getCourseById(courseId);
        if(course != null)
        {
            StudyCourseFileResponse rootFolder = buildFileTree(course.getFolderId());
            return rootFolder;
        }

        return null;
    }


    private StudyCourseFileResponse buildFileTree(Long folderId) {
        // 获取当前文件夹的信息
        StudyCourseFile folder =  studyCourseFileMapper.getCourseFileById(folderId);

        if (folder == null) {
            return null;
        }
        StudyCourseFileResponse folderResponse = new StudyCourseFileResponse();
        folderResponse.setCourseFileId(folder.getCourseFileId());
        folderResponse.setName(folder.getName());
        folderResponse.setParentId(folder.getParentId());
        folderResponse.setFilePath(folder.getFilePath());
        folderResponse.setCreatedAt(folder.getCreatedAt());
        folderResponse.setChildId(folder.getChildId());
        folderResponse.setCourseId(folder.getCourseId());

        // 获取子文件夹并递归构建子文件夹的响应
        List<StudyCourseFile> childFiles = studyCourseFileMapper.getFilesByParentId(folderId);
        //获取对应资源（文档和音视频）
        List<StudySourceFileResponse> studySourceFileResponses = getSourseFiles(folderId,"");
        folderResponse.setSourceFiles(studySourceFileResponses);

        //获取网页资源
        List<StudyWebSourse> webSourse = studyWebSourseMapper.getWebByCourseFileId(folderId);
        folderResponse.setWebSourses(webSourse);

        for (StudyCourseFile child : childFiles) {
            StudyCourseFileResponse childResponse = buildFileTree(child.getCourseFileId());
            if (childResponse != null) {
                folderResponse.getChildFiles().add(childResponse);
            }
        }

        return folderResponse;

    }

    @Override
    public List<StudySourceFileResponse> getSourseFiles(Long courseFileId,String sentence) {
        // 从三个资源表中获取在courseFileId下的那些资源
        List<StudySourceFileResponse> responseList = new ArrayList<>();
        // study_filesource
        List<StudyFileSource> studyFileSources = studyFileSourceMapper.selectList(new QueryWrapper<StudyFileSource>().eq("file_id", courseFileId));
        // 将 study_filesource 表中的资源转换为 StudySourceFileResponse
        for (StudyFileSource studyFileSource : studyFileSources) {
            StudySourceFileResponse response = new StudySourceFileResponse();
            response.setSourceId(studyFileSource.getFilesourceId());
            response.setCourseId(studyFileSource.getCourseId());
            response.setName(studyFileSource.getFileName());
            response.setSourcePath(studyFileSource.getFilesourcePath());
            response.setCreatedAt(studyFileSource.getCreatedAt());
            response.setTag("文档"); // 假设是文档类型的资源
            response.setOssWriteStatus(studyFileSource.getOssWriteStatus());
            response.setRagCompleteStatus(studyFileSource.getRagCompleteStatus());
            response.setSmartTextStatus(studyFileSource.getSmartTextStatus());
            response.setHandleCompleteStatus(studyFileSource.getHandleCompleteStatus());
            responseList.add(response);
        }

        // 从 coursesource 表中获取在 courseFileId 下的资源
        List<CourseSource> courseSources = courseSourceMapper.selectList(
                new QueryWrapper<CourseSource>().eq("file_id", courseFileId)
        );

        // 将 coursesource 表中的资源转换为 StudySourceFileResponse
        for (CourseSource courseSource : courseSources) {
            // 判断已上传未加工完的音视频资源的状态
//            if (!courseSource.getTranscriptionComplete() && courseSource.getOssWriteStatus()) {
//                String taskId = courseSource.getTaskId();
//                if (taskId != null && !taskId.isEmpty()) {
//                    Jugehandlevideostate(courseSource.getTaskId());
//                }
//            }
            StudySourceFileResponse response = new StudySourceFileResponse();
            response.setCourseId(courseSource.getCourseId());
            response.setSourceId(courseSource.getCourseSourceId());
            response.setName(courseSource.getFileName()); // 这里使用 language 字段作为名称，按需修改
            response.setSourcePath(courseSource.getFilesourcePath()); // 假设有一个路径，如果没有可以忽略
            response.setCreatedAt(courseSource.getCreatedAt());
            response.setTag("音视频"); // 假设是音视频类型的资源
            response.setOssWriteStatus(courseSource.getOssWriteStatus());
            response.setTranscriptionComplete(courseSource.getTranscriptionComplete());
            response.setTranscriptionCompleteStatus(courseSource.getTranscriptionCompleteStatus());
            responseList.add(response);
        }
        //依据sentence对 List<StudySourceFileResponse>中的Name进行过滤
        if (sentence != null && !sentence.isEmpty()) {
            responseList = responseList.stream()
                    .filter(response -> response.getName().contains(sentence))
                    .collect(Collectors.toList());
        }

        return responseList;
    }

    public List<StudySourceFileResponse> getSourseFilesBycourseId(Long courseId) {
        //从三个资源表中获取在courseFileId下的那些资源
        List<StudySourceFileResponse> responseList = new ArrayList<>();
        //study_filesource
        List<StudyFileSource> studyFileSources = studyFileSourceMapper.selectList(new QueryWrapper<StudyFileSource>().eq("course_id", courseId));
        // 将 study_filesource 表中的资源转换为 StudySourceFileResponse
        for (StudyFileSource studyFileSource : studyFileSources) {
            StudySourceFileResponse response = new StudySourceFileResponse();
            response.setSourceId(studyFileSource.getFilesourceId());
            response.setCourseId(studyFileSource.getCourseId());
            response.setName(studyFileSource.getFileName());
            response.setSourcePath(studyFileSource.getFilesourcePath());
            response.setCreatedAt(studyFileSource.getCreatedAt());
            response.setTag("文档"); // 假设是文档类型的资源
            response.setOssWriteStatus(studyFileSource.getOssWriteStatus());
            response.setRagCompleteStatus(studyFileSource.getRagCompleteStatus());
            response.setSmartTextStatus(studyFileSource.getSmartTextStatus());
            response.setHandleCompleteStatus(studyFileSource.getHandleCompleteStatus());
            responseList.add(response);
        }
        // 从 coursesource 表中获取在 courseFileId 下的资源
        List<CourseSource> courseSources = courseSourceMapper.selectList(
                new QueryWrapper<CourseSource>().eq("course_id", courseId)
        );

        // 将 coursesource 表中的资源转换为 StudySourceFileResponse
        for (CourseSource courseSource : courseSources) {
            // 判断已上传未加工完的音视频资源的状态
//            if (!courseSource.getTranscriptionComplete() && courseSource.getOssWriteStatus()) {
//                String taskId = courseSource.getTaskId();
//                if (taskId != null && !taskId.isEmpty() ) {
//                    Jugehandlevideostate(courseSource.getTaskId());
//                }
//            }
            StudySourceFileResponse response = new StudySourceFileResponse();
            response.setCourseId(courseSource.getCourseId());
            response.setSourceId(courseSource.getCourseSourceId());
            response.setName(courseSource.getFileName()); // 这里使用 language 字段作为名称，按需修改
            response.setSourcePath(courseSource.getFilesourcePath()); // 假设有一个路径，如果没有可以忽略
            response.setCreatedAt(courseSource.getCreatedAt());
            response.setTag("音视频"); // 假设是音视频类型的资源
            response.setOssWriteStatus(courseSource.getOssWriteStatus());
            response.setTranscriptionComplete(courseSource.getTranscriptionComplete());
            response.setTranscriptionCompleteStatus(courseSource.getTranscriptionCompleteStatus());
            responseList.add(response);
        }

        return responseList;
    }
    @Override
    public List<StudySourceFileResponse> getSourseFilesALL(String userId,String sentence) {
        //从三个资源表中获取在courseFileId下的那些资源
        List<StudySourceFileResponse> responseList = new ArrayList<>();

        List<StudyTeacherCourse> courses = studyTeacherCourseMapper.getCourseByteacherId(userId);
        for (StudyTeacherCourse course : courses) {
            responseList.addAll(getSourseFilesBycourseId(course.getCourseId()));
        }
        if (sentence != null && !sentence.isEmpty()) {
            responseList = responseList.stream()
                    .filter(response -> response.getName().contains(sentence))
                    .collect(Collectors.toList());
        }
        return responseList;
    }

    //查询转写状况，并在完成时写入转写结果
    public R Jugehandlevideostate(String taskId,int queryNum) {
//        FileTranscriptionTaskResponse result =f ileTranscriptionMapper.selectById(taskId);
//        String sourcePath=result.getOutput_mp3_path();
        CourseSource courseSource = courseSourceMapper.selectOne(new QueryWrapper<CourseSource>().eq("task_id", taskId));
        try {
            R result = fileTranscriptionController.getResult(taskId,courseSource.getFilesourcePath());
            log.info("查询结果为："+result);
            if (result.getCode()==1 ) {
                FileTranscriptionTaskResponse data = (FileTranscriptionTaskResponse) result.getData();
                if (data.getTaskStatus().equals("COMPLETED")){
                    courseSource.setTranscriptionComplete(true);
                    courseSource.setTranscriptionCompleteStatus(true);
                    courseSourceMapper.updateById(courseSource);
                } else if (data.getTaskStatus().equals("FAILED")) {
                    courseSource.setTranscriptionCompleteStatus(true);
                    courseSourceMapper.updateById(courseSource);
                    logger.info("音视频{}加工失败原因{}：",taskId ,data.getErrorMessage());
                }
            }
            return result;
        }
        catch (Exception e) {
            log.error("查询音视频加工状态时出现异常: " + taskId, e);
            if (queryNum>5){
                //请求结果失败也算加工失败
                courseSource.setTranscriptionCompleteStatus(true);
                courseSourceMapper.updateById(courseSource);
                log.error("第六次请求音视频加工状态且请求异常,视作音视频处理失败"+e.getMessage());
            }

            return R.failure("音视频处理失败");
        }

    }

}


